package MergeExcel;

import Utils.Tools;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class 高管持股 {

    public static void main(String[] args) throws IOException {
        List<String> excelPaths = Tools.GetAllFilePath("E:\\choice抓取\\高管持股3");
        List<List<String>> rowList = new ArrayList<>();
        for (String excelPath : excelPaths){
            rowList.addAll(getRow(excelPath));
        }

        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        sheet.createRow(0);
        int rowIndex = 1;
        for(List<String> colData : rowList){
            Row row = sheet.createRow(rowIndex++);
            if (colData.size() == 0){
                continue;
            }
            for (int i = 0; i < colData.size(); i++) {
                row.createCell(i).setCellValue(colData.get(i));
            }
        }

        workbook.write(new FileOutputStream("D:\\测试临时文件\\mergeExcel.xlsx"));
    }

    public static List<List<String>> getRow(String excelPath) throws IOException {
        System.out.println("正在读取"+excelPath);
        Workbook workbook = WorkbookFactory.create(new File(excelPath));
        Sheet sheet = workbook.getSheetAt(0);

        List<List<String>> resList = new ArrayList<>();

        List<String> temp = new ArrayList<>();
        temp.add(excelPath.replace("E:\\choice抓取\\高管持股3\\", ""));
        resList.add(temp);

        int RowSize = sheet.getPhysicalNumberOfRows();
        for (int i = 1; i < RowSize; i++) {
            Row row = sheet.getRow(i);

            if (row == null){
                resList.add(new ArrayList<>());
                break;
            }

            List<String> colData = new ArrayList<>();
            for (int j = 0; j < 7; j++) {
                colData.add(row.getCell(j) + "");
            }
            resList.add(colData);

        }

        return resList;
    }

}
